<template>
  <continer :isNoTabs="true">
    <template slot="search">
      <QuickSearch
        :advForm="quickSearchForm"
        @QuickSearch="handleSearchFunc"
      ></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button
        type="primary"
        v-functions="['notice_create']"
        size="mini"
        @click="addNotice"
        ><i
          class="V7_iconV7tubiao_xinzeng V7_iconfont"
          style="padding-right: 5px; font-size: 12px"
        ></i
        >新建公告</el-button
      >
    </template>
    <template slot="content">
      <!-- 表格 -->
      <configTable
        ref="table"
        :headers="tableHeaders"
        :data="noticeTableData"
        :batchs="batchs"
        :pagingData="pagingData"
        @pageChange="handleCurrentChange"
        @pageSizeChange="handleSizeChange"
        @checkHeadersChange="checkHeadersChange"
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              v-if="item.prop === 'title'"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="false"
              :sortable="item.sortable"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.title }}</span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.prop === 'level'"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :width="100"
              :resizable="false"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.level === 'common'">普通</span>
                <span v-else>重要</span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.prop === 'updateTime'"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :width="150"
              :resizable="false"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.updateTime }}</span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.prop === 'updateAgent'"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="false"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <span>{{ getAgentName(scope.row.updateAgent) }}</span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.prop === 'publishTime'"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :width="150"
              :resizable="false"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.publishTime }}</span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.prop === 'day'"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :width="80"
              :resizable="false"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <div style="text-align: center">{{ scope.row.day }}</div>
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.prop === 'status'"
              :key="index"
              :label="item.label"
              :width="80"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.status === 'save'">已保存</span>
                <span v-if="scope.row.status === 'publish'">已发布</span>
                <span v-if="scope.row.status == 'disable'">已失效</span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.show && item.prop === 'oprate'"
              :key="index"
              :label="item.label"
              :width="item.width"
              fixed="right"
            >
              <template slot-scope="scope">
                <span
                  class="oprate-span"
                  @click="openRangeDrawer(scope.row)"
                  v-functions="['notice_show_scope']"
                  >公示范围</span
                >
                <span
                  class="oprate-span"
                  @click="handleEdit(scope.row)"
                  v-if="scope.row.status === 'save'"
                  v-functions="['notice_update']"
                  >编辑</span
                >
                <span
                  class="oprate-span red-span"
                  @click="handleDelete(scope.row)"
                  v-functions="['notice_del']"
                  >删除</span
                >
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
      <cuDrawer
        ref="cuDrawer"
        :drawerType="drawerType"
        :postForm="postForm"
        @rederData="rederData"
      ></cuDrawer>
      <RangeDrawer ref="rangeDrawer"> </RangeDrawer>
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import QuickSearch from '@/components/globalTool/search/index.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import cuDrawer from './NoticeDrawer.vue'
import configTable from '@/components/configCommon/table.vue'
import { commonAction, isHasFuncOrMenus } from '@/utils/common'
import RangeDrawer from './RangeDrawer.vue'
import { DefaultForm, PageData } from './notice'
import { CommonModule } from '@/store/modules/common'
const defaultForm: DefaultForm = {
  title: '',
  content: '',
  attachs: [],
  showDays: {
    type: 'system',
    value: undefined
  },
  level: 'common',
  showScope: {
    role: '',
    queue: '',
    user: '',
    dept: ''
  }
}
@Component({
  name: 'NoticeSetting',
  components: {
    QuickSearch,
    configTable,
    cuDrawer,
    continer,
    RangeDrawer
  }
})
export default class NoticeSetting extends Vue {
  [x: string]: any
  @Ref() private readonly cuDrawer: any
  @Ref() private readonly rangeDrawer: any
  private drawerType: string = 'add'
  private noticeTableData: any = []
  private pagingData: PageData = { total: 0, limit: 10, page: 1 }
  private checkHeaders: [] = []
  private postForm = {}
  private statusSelect = [
    { _id: 'save', name: '已保存' },
    { _id: 'publish', name: '已发布' },
    { _id: 'disable', name: '已失效' }
  ]

  private levelSelect = [
    { _id: 'common', name: '普通' },
    { _id: 'import', name: '重要' }
  ]

  private quickSearchForm: any = {
    form: {
      title: '',
      date: [],
      status: '',
      level: ''
    },
    advSearchOptions: [
      { label: '公告标题', name: 'title', inputType: 'input', clearable: true, placeholder: '请输入关键字' },
      { label: '发布日期', name: 'date', inputType: 'dateRange', clearable: true },
      { label: '公告状态', name: 'status', inputType: 'select', clearable: true, selectData: this.statusSelect, placeholder: '请选择' },
      { label: '公示级别', name: 'level', inputType: 'select', clearable: true, selectData: this.levelSelect, placeholder: '请选择' }
    ]
  }

  private async mounted () {
    (this as any).$getCache('/base/action/general/cache/query', ['roleList', 'queueList', 'userList', 'departmentList'], true).then((data: any) => {
      this.getData()
    })
  }

  private getAgentName (agentId) {
    const agent = (CommonModule as any).publicCache.userListObj[agentId]
    if (agent) {
      return agent.name
    }
    return ''
  }

  private async getData () {
    const actionData: any = {
      limit: this.pagingData.limit,
      page: this.pagingData.page,
      level: this.quickSearchForm.form.level,
      status: this.quickSearchForm.form.status,
      title: this.quickSearchForm.form.title
    }
    if (this.quickSearchForm.form.date) {
      actionData.publishTimeBegin = this.quickSearchForm.form.date[0]
      actionData.publishTimeEnd = this.quickSearchForm.form.date[1]
    }
    const data: any = await commonAction({ url: '/base/action/notice/queryNoticeList', method: 'POST', data: actionData })
    if (data.success) {
      this.noticeTableData = data.data.list.map(v => {
        const day = v.showDays.value
        return {
          ...v,
          day
        }
      })
      this.pagingData.total = data.data.count
    }
  }

  private handleSearchFunc () {
    this.pagingData.page = 1
    this.getData()
  }

  private tableHeaders: object[] = [
    { label: '公告标题', prop: 'title' },
    { label: '公示级别', prop: 'level' },
    { label: '最后操作时间', prop: 'updateTime' },
    { label: '最后操作人', prop: 'updateAgent' },
    { label: '发布时间', prop: 'publishTime' },
    { label: '公示期(天)', prop: 'day' },
    { label: '公告状态', prop: 'status' }
  ]

  private beforeMount () {
    let width = 30
    const arr = [
      'notice_show_scope',
      'notice_update',
      'notice_del'
    ]
    // 新增，停用/启用， 编辑，配置，删除
    arr.forEach((item: string) => {
      if (isHasFuncOrMenus(item, this.$store.state.common.session.user, false)) {
        width += 30
      }
    })
    if (width > 30) {
      this.tableHeaders.push({ label: '操作', prop: 'oprate', width })
    }
  }

  private addNotice () {
    this.drawerType = 'add';
    this.postForm = defaultForm
    this.cuDrawer.openDraw()
  }

  private async handleEdit (row) {
    this.drawerType = 'edit';
    const params = { url: '/base/action/notice/getNoticeById', method: 'POST', data: { id: row._id } }
    const result: any = await commonAction(params)
    if (result.success) {
      const { data } = result
      if (data) {
        this.postForm = data
        this.cuDrawer.openDraw()
      } else {
        this.$message.error('公告已被删除，无法编辑')
      }
    }
  }

  private rederData (type: string) {
    this.handleSearchFunc()
  }

  private openRangeDrawer (row: any) {
    this.rangeDrawer.openDraw(row)
  }

  private handleDelete (row: any) {
    this.$confirm('删除后将无法找回，是否删除公告？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const actionData = { id: row._id }
      const params = { url: '/base/action/notice/delete', method: 'POST', data: actionData }
      const data: any = await commonAction(params)
      if (data.success) {
        this.$message.success('删除成功')
        this.getData()
      }
    })
  }

  private checkHeadersChange (checkList) {
    this.$set(this, 'checkHeaders', checkList)
  }

  private handleSizeChange (size: number) {
    this.pagingData.limit = size
    this.handleSearchFunc()
  }

  private handleCurrentChange (page: number) {
    this.pagingData.page = page
    this.getData()
  }
}
</script>
<style lang="stylus" scoped>
.oprate-span
  cursor pointer
  color $c-main
  margin 0 4px
.red-span, .disable-span
  color $c-danger
.enable-span
  color $c-green
.disable-span, .enable-span
  font-size 12px
</style>
